package com.winit.common.filter;

import com.winit.common.util.NetworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SessionValidFilter implements Filter {

    private Logger log = LoggerFactory.getLogger(SessionValidFilter.class);

    public void destroy() {

    }

    private String request_allow_ips;

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        // 做权限控制
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        String url = request.getRequestURI();// 用户请求地址
        String ip = NetworkUtil.getIpAddress(request);
        log.info("com.winit.common.filter.SessionValidFilter.doFilter,url=" + url + ",ip=" + ip);

        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        if ("/api/v1/ogg/noPower".equals(url)) {
            chain.doFilter(req, res);
            return;
        }

        if (!request_allow_ips.contains("," + ip + ",")) {
            log.info("com.winit.common.filter.SessionValidFilter.doFilter,没有访问权限,url=" + url + ",ip=" + ip);
            redirect(response, "/api/v1/ogg/noPower");
            return;
        }
        chain.doFilter(req, res);
    }


    public void init(FilterConfig config) throws ServletException {
        // TODO Auto-generated method stub
        this.request_allow_ips = config.getInitParameter("request_allow_ips");
    }

    private void redirect(HttpServletResponse response, String url)
            throws IOException {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);

        response.sendRedirect(url);
    }
}
